﻿using NewRen.Helpers;
using NewRen.Models;
using NewRen.Schemas;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{

    [Schema.LoginCheck]
    public class SystemController : BaseController
    {
        // GET: Admin/System
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult EditAvatar(int id)
        {
            var admin = db.Admins.Find(id);
            return View(admin);
        }

        #region 管理员修改图像
        /// <summary>
        /// 管理员修改图像
        /// </summary>
        /// <param name="file"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditAvatar(HttpPostedFileBase file, int id)
        {
            var admin = db.Admins.Find(id);
            try
            {
                System.IO.Stream stream = file.InputStream;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, (int)stream.Length);
                stream.Close();
                admin.Picture = buffer;
                db.SaveChanges();
                return Redirect("/Admin/Home/Index");
            }
            catch
            {
                return View(admin);
            }

        }

        #endregion



        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult EditPwd(int id)
        {
            var admin = db.Admins.Find(id);
            return View(admin);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditPwd(int ID, string Old, string Password, string Confirm)
        {
            var admin = db.Admins.Find(ID);
            if (ModelState.IsValid)
            {
                if (admin.Password.Equals(Helpers.Encryt.GetMD5(Old)))
                {
                    if (Password.Equals(Confirm))
                    {
                        try
                        {
                            admin.Password = Helpers.Encryt.GetMD5(Password);
                            db.SaveChanges();
                            Redirect("/Admin/System/Index");
                        }
                        catch
                        {
                            ModelState.AddModelError("", "修改密码出现错误！");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "两输入密码不一致！");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "原始密码不正确！");
                }

            }
            else
            {
                ModelState.AddModelError("", "你填写的信息由错误！");
            }
            return View(admin);
        }
        #endregion



        #region 管理员管理
        /// <summary>
        /// 管理员管理
        /// </summary>
        /// <param name="key"></param>
        /// <param name="Begin"></param>
        /// <param name="End"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public ActionResult Manager(string key, DateTime? Begin, DateTime? End, int p = 0)
        {
            var query = db.Admins.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(a => a.RealName.Contains(key) || a.UserName.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(a => a.Time >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(a => a.Time <= End);
            }
            query = query.OrderByDescending(a => a.RoleAsInt).ThenByDescending(a => a.Time);
            ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
            return View(query);
        }

        [HttpGet]
        public ActionResult AdminShow(int id)
        {
            var admin = db.Admins.Find(id);
            return View(admin);
        }

        [HttpGet]
        public ActionResult ShowAdminPicture(int id)
        {
            Models.Admin admin = new Models.Admin();
            admin = db.Admins.Find(id);
            return File(admin.Picture, "image/jpg");
        }

        [HttpPost]
        [ValidateSID]
        public ActionResult DeleteAdmin(int id)
        {
            Models.Admin admin = new Models.Admin();
            admin = db.Admins.Find(id);
            db.Admins.Remove(admin);
            db.SaveChanges();
            return Content("ok");
        }

        /// <summary>
        /// 修改管理员信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AdminEditPwd(int id)
        {
            Models.Admin admin = new Models.Admin();
            admin = db.Admins.Find(id);
            return View(admin);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AdminEditPwd(string Password, int ID)
        {
            Models.Admin admin = new Models.Admin();
            admin = db.Admins.Find(ID);
            if (ModelState.IsValid)
            {
                try
                {
                    admin.Password = Helpers.Encryt.GetMD5(Password);
                    db.SaveChanges();
                    return Redirect("/Admin/System/Manager");
                }
                catch
                {
                    ModelState.AddModelError("", "修改密码失败，请重试！");
                }

            }
            else
            {
                ModelState.AddModelError("", "信息填写不正确！");
            }
            return View(admin);
        }


        /// <summary>
        /// 增加管理员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddAdmin()
        {
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddAdmin(Models.Admin model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var admin = db.Admins.Where(a => a.UserName == model.UserName).FirstOrDefault();
                    if (admin != null)
                    {
                        ModelState.AddModelError("", "该用户名已经存在！");
                        return View();
                    }
                    model.Password = Helpers.Encryt.GetMD5(model.Password);
                    model.Time = DateTime.Now;
                    db.Admins.Add(model);
                    db.SaveChanges();
                    return Redirect("/Admin/System/Manager");
                }
                catch
                {
                    ModelState.AddModelError("", "添加失败，请重试！");
                }
            }
            else
            {
                ModelState.AddModelError("", "信息填写不正确");
            }
            return View();
        }

        #endregion


        #region 系统参数设置
        /// <summary>
        /// 系统参数设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Setting(int page = 1)
        {
            var settings = db.SysSettings.OrderBy(s => s.ID).ToPagedList(page, 20);

            return View(settings);
        }

        /// <summary>
        /// 增加参数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddSetting()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddSetting(SysSetting model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db.SysSettings.Add(model);
                    db.SaveChanges();
                    return Redirect("/Admin/System/Setting");
                }
                catch
                {
                    ModelState.AddModelError("", "添加系统参数出错！");
                }
            }
            else
            {
                ModelState.AddModelError("", "你填写的信息有误");
            }
            return View();
        }

        /// <summary>
        /// 删除参数设置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [ValidateSID]
        [HttpPost]
        public ActionResult DeleteSetting(int id)
        {
            try
            {
                var setting = db.SysSettings.Find(id);
                db.SysSettings.Remove(setting);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("err");
            }
        }

        /// <summary>
        /// 显示参数设置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SettingShow(int id)
        {
            var setting = db.SysSettings.Find(id);
            return View(setting);
        }

        [HttpGet]
        public ActionResult SettingEdit(int id)
        {
            var setting = db.SysSettings.Find(id);
            return View(setting);
        }

        [HttpPost]
        public ActionResult SettingEdit(SysSetting model)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    var settting = db.SysSettings.Find(model.ID);
                    settting.Key = model.Key;
                    settting.Value = model.Value;
                    db.SaveChanges();
                    return Redirect("/Admin/System/Setting");
                }
                catch
                {
                    ModelState.AddModelError("", "修改失败！");
                }
               
            }
            else
            {
                ModelState.AddModelError("","填写信息错误");
            }
            return View();
        }

        #endregion
    }
}